package com.lixw.aiassistant.controller;

import com.lixw.aiassistant.handler.ChainEnum;
import com.lixw.aiassistant.handler.ChatChainHandler;
import com.lixw.aiassistant.model.memory.RecognizedIntent;
import com.lixw.aiassistant.result.Result;
import com.lixw.aiassistant.service.IntentRecognitionService;
import com.lixw.aiassistant.service.MemoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.Message;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/chat")
public class ChatController {
    
    @Resource
    private IntentRecognitionService intentRecognitionService;
    
    @Resource
    private MemoryService memoryService;

    @GetMapping(value = "/stream")
    public Flux<String> streamChat(
            @RequestParam String sessionId,
            @RequestParam String question) {

        log.info("streamChat sessionId: {}, question: {}", sessionId, question);
        // 1. 意图识别（会考虑历史对话）
        RecognizedIntent recognizeIntent = intentRecognitionService.recognizeIntent(question,sessionId);

        // 2. 使用策略枚举类调用不同的链
        ChainEnum chainEnum = ChainEnum.getByCode(recognizeIntent.getIntent());
        ChatChainHandler chainHandler = chainEnum.getHandler();
        Flux<String> handle = chainHandler.handle(sessionId,question);
        // 5. 保存AI响应到记忆
        return handle
                .doOnNext(response -> log.info("会话id:{},智能客服返回消息:{}", sessionId, response));
    }

    @GetMapping("/history/{sessionId}")
    public Result<List<Message>> getConversationHistory(@PathVariable String sessionId) {
        return Result.ok(memoryService.getConversationContext(sessionId));
    }
    
    @DeleteMapping("/history/{sessionId}")
    public Result<String> clearConversationHistory(@PathVariable String sessionId) {
        memoryService.clearSession(sessionId);
        return Result.ok("对话历史已清除");
    }
    
    @GetMapping("/health")
    public Result<String> health() {
        return Result.ok("智能客服系统运行正常");
    }
}